package du.myseckill.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import du.myseckill.dao.UserDao;
import du.myseckill.dto.Login;
import du.myseckill.dto.Register;
import du.myseckill.pojo.User;
import du.myseckill.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private static String salt = "124691246#$^%*^(^dhuhdkw";

    @Autowired
    private UserDao userDao;

    @Override
    public Login login(String userName, String password) {
        User user = userDao.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, userName));
        if (user == null) {
            return new Login(false, "用户不存在");
        }
        String base = password + "/" + salt;
        String passwordMd5 = DigestUtils.md5DigestAsHex(base.getBytes());
        if (!user.getPassword().equals(passwordMd5)) {
            return new Login(false, "密码错误");
        }
        return new Login(true, "登陆成功", user.getUserId(),user.getUserPhone());
    }

    @Override
    public Register register(String userName, String password, long userPhone) {
        User user = userDao.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, userName));
        if (user != null) {
            return new Register(false, "用户已存在");
        }
        String base = password + "/" + salt;
        String passwordMd5 = DigestUtils.md5DigestAsHex(base.getBytes());
        if (userPhone < 10000000000L || userPhone > 100000000000L) {
            return new Register(false, "请输入正确的手机号码");
        }
        int insert = userDao.insert(User.builder()
                .userName(userName)
                .password(passwordMd5)
                .userPhone(userPhone)
                .build());
        if (insert == 1) {
            return new Register(true, "注册成功！", userName);
        } else {
            return new Register(false, "系统错误！");
        }
    }

    @Override
    public long getPhoneByName(String userName) {
        User user = userDao.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, userName));
        if(user!=null){
            long userPhone = user.getUserPhone();
            return userPhone;
        }
        return -1;    }
}
